from odoo import fields, models, api


class SaleOrder(models.Model):
    _inherit = "sale.order"

    sb_fo_line_id = fields.Many2one('s.forecast.order.line', string="FO")  # don't use 0930 视情况去除
    sb_fo_line_ids = fields.Many2many('s.forecast.order.line', string="FO")

    # @api.constrains('sb_fo_line_id', 'status')
    # def constrains_sb_fo_line_id(self):
    #     for sale in self:
    #         if not sale.sb_fo_line_id:
    #             continue
    #         product_lock_ids = self.env['s.product.lock'].search([('forecast_order_line_id', '=', sale.sb_fo_line_id.id)])
    #         if not product_lock_ids:
    #             continue
    #         line_ids = sale.order_line.filtered(lambda x: x.product_id.detailed_type == 'product')
    #         if line_ids:
    #             line = line_ids[0]
    #             product_lock_ids.update({'sale_id': sale.id, 'sale_order_line_id': line.id})
    #             line.s_pm_quantity = min(product_lock_ids.mapped('qty'))

    def action_view_fo(self):
        self.ensure_one()
        action = self.env.ref('sb_forecast_order.forecast_order_action').read()[0]
        fo_ids = list(set(self.sb_fo_line_ids.mapped('forecast_order_id.id')))
        if len(fo_ids) == 1:
            form_view = self.env.ref('sb_forecast_order.forecast_order_view_form')
            action['views'] = [(form_view.id, 'form')]
            action['res_id'] = fo_ids[0]
            action.pop('domain', None)
        else:
            action['domain'] = [('id', 'in', fo_ids)]
            action.pop('res_id', None)

        return action
